package com.tech.thread.sync;

/**
 * @Description:
 * @Author: zl
 * @Date: 2019/7/23 17:09
 */
public class SingletonDemo {
    private static SingletonDemo instance = null;

    private SingletonDemo() {
    }

    public static SingletonDemo getInstance() throws InterruptedException {
        if (instance == null) {
            // 多个线程躲避了 第一个校验 到达此处，进行锁竞争，得到锁开始执行对象创建未得到锁的开始等待，当重新获得锁开始执行
            // 由此可见如果没有第二个校验依旧会创建多个实例
            synchronized (SingletonDemo.class) {
                Thread.sleep(100);
                if (instance == null) {
                    instance = new SingletonDemo();
                }
                return instance;
            }
        }
        return instance;
    }

    public static void main(String[] args) {
        for (int i = 0; i < 5; i++) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    SingletonDemo demo = null;
                    try {
                        demo = SingletonDemo.getInstance();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(demo);
                }
            }).start();
        }
    }
}


